<template>
  <div class="container" style="padding: 0 10px; border-top: 1px solid #ccc">
    <div class="flex_js p_10_0">
      <div
        class="top_title"
        @click="(show_num_table = !show_num_table), EventBus.emit('show_num_table');"
      >
        编号列表
        <img
          src="@/assets/img/menu_icon_right.png"
          style="width: 14px; height: 14px; margin-left: 5px"
          alt=""
          :class="show_num_table ? 'select_me' : ''"
        />
      </div>
      <div class="flex">
        <el-button
          type="primary"
          class="m_right20"
          @click="add_fun"
          v-if="
            has_role_list[0].has_role &&
            store.state.current_enterprise_level.some((i) => {
              return i.productId == '2' && ['3', '4'].includes(i.levelId);
            }) &&
            add_form_data.identifierId != ''
          "
          >新增</el-button
        >
      </div>
    </div>
    <div v-show="show_num_table">
      <el-table
        :data="list"
        border
        ref="table"
        class="tc"
        :max-height="max_height"
        highlight-current-row
        v-loading="loading"
        :row-style="{
          height: height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
        :row-class-name="
          ({ row, rowIndex }) => {
            row.index = rowIndex;
          }
        "
        @row-click="
          (row) => {
            currentRowIndex = row.index;
            get_list_info(row.id);
          }
        "
      >
        <el-table-column label="序号" type="index" width="80px"></el-table-column>
        <el-table-column label="铝模板编号格式" width="150px" sortable prop="table_code">
        </el-table-column>
        <el-table-column label="图纸类型" sortable prop="drawingType" width="120px">
          <template #default="scope: any">
            <div v-if="scope.row.drawingType == 1">大样图</div>
            <div v-else>生产图</div>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sort" width="100px">
          <template #default="scope: any">
            <el-input
              style="text-align: center"
              v-model="scope.row.sort"
              @focus.stop="current_sort = JSON.parse(JSON.stringify(scope.row.sort))"
              @blur="change_sort(scope.row)"
              :disabled="
                !has_role_list[0].has_role ||
                !store.state.current_enterprise_level.some((i) => {
                  return i.productId == '2' && ['3', '4'].includes(i.levelId);
                })
              "
            ></el-input> </template
        ></el-table-column>
        <el-table-column
          label="大样图编号"
          width="150px"
          sortable
          prop="figureNo"
        ></el-table-column>
        <el-table-column
          label="主代号"
          width="100px"
          sortable
          prop="mainCode"
          v-if="props.rule_type != 2"
        >
          <template #default="scope: any">
            <el-input
              style="text-align: center"
              v-model="scope.row.mainCode"
              @focus.stop="get_mainCode(scope.row)"
              @blur="change_sort(scope.row)"
              :disabled="
                !has_role_list[0].has_role ||
                !store.state.current_enterprise_level.some((i) => {
                  return i.productId == '2' && ['3', '4'].includes(i.levelId);
                })
              "
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remark"
          show-overflow-tooltip
          sortable
        ></el-table-column>
        <el-table-column
          label="操作"
          width="230px"
          fixed="right"
          v-if="
            has_role_list[0].has_role &&
            store.state.current_enterprise_level.some((i) => {
              return i.productId == '2' && ['3', '4'].includes(i.levelId);
            })
          "
        >
          <template #default="scope: any">
            <div class="flex_cc" style="column-gap: 20px">
              <el-tooltip content="编辑" placement="bottom">
                <svgBtn
                  icon="table_edit"
                  style="font-size: 20px"
                  @click="edit_list(scope.row)"
                ></svgBtn>
              </el-tooltip>
              <el-tooltip content="上移" placement="bottom" v-if="scope.$index > 0">
                <svgBtn
                  icon="table_move"
                  style="font-size: 20px"
                  @click="move_list({ item: scope.row, type: 1, index: scope.$index })"
                ></svgBtn>
              </el-tooltip>
              <el-tooltip
                content="下移"
                placement="bottom"
                v-if="scope.$index < list?.length - 1"
              >
                <svgBtn
                  icon="table_move"
                  style="font-size: 20px; transform: rotate(180deg)"
                  @click="move_list({ item: scope.row, type: 2, index: scope.$index })"
                ></svgBtn>
              </el-tooltip>
              <el-tooltip content="复制" placement="bottom">
                <svgBtn
                  icon="fuzhi"
                  color="#333"
                  style="font-size: 20px"
                  @click="copy_list(scope.row)"
                ></svgBtn>
              </el-tooltip>
              <el-tooltip content="删除" placement="bottom">
                <svgBtn
                  icon="table_delete"
                  style="font-size: 20px"
                  @click="delete_list({ item: scope.row, type: 0 })"
                ></svgBtn>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="m_10_0"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 100, 500]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list_debounce()"
        @current-change="list_debounce()"
      />
    </div>
  </div>
  <el-drawer
    v-model="show_box"
    direction="rtl"
    size="50%"
    destroy-on-close
    :close-on-click-modal="false"
    @close="resetForm(addnumlistform)"
  >
    <template #title>
      <h4 v-if="add_form_data.id == ''">新增编号</h4>
      <h4 v-else>编辑编号</h4>
    </template>
    <template #default>
      <el-form
        :model="add_form_data"
        ref="addnumlistform"
        :rules="rules"
        label-width="100px"
      >
        <div>
          <div class="table_header">
            <span style="width: 10%">序号</span>
            <span style="width: 30%">参数类型</span>
            <span style="width: 30%">参数值</span>
            <span style="width: 20%">排序</span>
            <span style="width: 10%">操作</span>
          </div>
          <div
            class="table_header"
            v-for="(item, index) in add_table"
            :key="index"
            style="background-color: #fff; border-top: none"
          >
            <div class="flex_js flex1">
              <span style="width: 10%">{{ index + 1 }}</span>
              <span style="width: 30%">
                <el-select
                  v-model="item.type"
                  style="width: 80%"
                  @change="item.value = ''"
                >
                  <el-option label="属性" value="1"></el-option>
                  <el-option label="代号" value="2"></el-option>
                </el-select>
              </span>
              <span style="width: 30%">
                <el-select
                  v-model="item.value"
                  v-if="item.type == '1'"
                  style="width: 80%"
                >
                  <el-option
                    v-for="item in metadata_list"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
                <el-input
                  v-model="item.value"
                  v-else
                  style="width: 80%"
                  show-word-limit
                  maxlength="30"
                ></el-input>
              </span>
              <span style="width: 20%">{{ index + 1 }}</span>
              <span style="width: 10%"
                ><el-button @click="add_table.splice(index, 1)">删除</el-button></span
              >
            </div>
          </div>
          <el-button type="primary" class="m_top10" @click="add_table_row"
            >追加一行</el-button
          >
        </div>
        <el-form-item label="图纸类型" prop="drawingType">
          <el-select v-model="add_form_data.drawingType">
            <el-option label="大样图" value="1"></el-option>
            <el-option label="生产图" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="大样图编号">
          <el-input
            placeholder="请输入"
            v-model="add_form_data.figureNo"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="主代号" v-if="props.rule_type != 2">
          <el-input
            placeholder="请输入"
            v-model="add_form_data.mainCode"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="序号">
          <el-input
            placeholder="请输入"
            v-model="add_form_data.sort"
            show-word-limit
            maxlength="3"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序" v-if="add_form_data.id == ''">
          <div class="flex">
            <el-radio v-model="add_form_data.sort_type" :label="1">增至列表最后</el-radio>
            <el-radio v-model="add_form_data.sort_type" :label="2">增至列表最前</el-radio>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            placeholder="请输入"
            v-model="add_form_data.remark"
            show-word-limit
            maxlength="100"
          ></el-input>
        </el-form-item>
        <div class="tr m_top10">
          <el-button @click="resetForm(addnumlistform)">取消</el-button>
          <el-button type="primary" @click="submit(addnumlistform)" :loading="btn_loading"
            >确定</el-button
          >
        </div>
      </el-form>
    </template>
  </el-drawer>
  <dialog_box
    @submit_delete="submit_delete"
    @close="show_delete_box = false"
    :delete_name="delete_name"
    :show_delete_box="show_delete_box"
    :delete_box_status="delete_box_status"
  ></dialog_box>
</template>

<script lang="ts" setup>
import { debounce, check_role } from "@/utils/check_role"; // 权限校验
import dialog_box from "@/view/components/dialog_box.vue";
import { onMounted, ref, onUnmounted } from "vue";
import { FormInstance, ElMessage } from "element-plus";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
import svgBtn from "@/components/svg_button.vue";
import { useStore } from "vuex";
// type FormInstance = InstanceType<typeof ElForm>
const addnumlistform = ref<FormInstance>();
const rules = ref({
  drawingType: [{ required: true, message: "", trigger: "change" }],
  sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
});
const props = defineProps({
  rule_type: Number,
});
const store = useStore();
const has_role_list = ref(
  props.rule_type == 1
    ? [{ path: "mouldIdentifier/post", has_role: false }]
    : props.rule_type == 2
    ? [{ path: "partsIdentifier/post", has_role: false }]
    : [{ path: "partsselfIdentifier/post", has_role: false }]
);
const current_sort = ref();
const current_mainCode = ref();
const get_mainCode = (e) => {
  console.log(e);
  if (e.mainCode == "") {
    current_mainCode.value = "";
    let list = e.code.split("}{");
    list[0] = list[0].replace("{", "");
    list[list.length - 1] = list[list.length - 1].replace("}", "");
    list.some((item) => {
      if (item.search("%") == -1 && parseFloat(item).toString() == "NaN") {
        console.log(item);
        e.mainCode = item;
      }
      return item.search("%") == -1 && parseFloat(item).toString() == "NaN";
    });
  } else {
    current_mainCode.value = e.mainCode;
  }
};
const change_sort = (e) => {
  console.log(e);
  if (
    (current_sort.value != "" && current_sort.value != e.sort) ||
    current_mainCode.value != e.mainCode
  ) {
    axios
      .request({
        url: serviceApi.change_sort,
        method: "post",
        data: { list: [{ id: e.id, sort: e.sort, mainCode: e.mainCode }] },
      })
      .then((res) => {
        console.log(res);
        current_mainCode.value = current_mainCode.value != "" ? e.mainCode : "";
        ElMessage.success("操作成功！");
        list.value.sort((a, b) => {
          return a.sort - b.sort;
        });
      })
      .catch((err) => {
        ElMessage.error(err);
      });
  } else {
    current_sort.value = "";
  }
};
const height_size = ref(1);
const show_box = ref(false);
const page_data = ref({
  current: 1,
  pageSize: 10,
  identifierId: "",
});
const add_form_data = ref({
  id: "",
  identifierId: "",
  code: "",
  drawingType: "1",
  figureNo: "",
  sort: "",
  mainCode: "",
  sort_type: 1,
  remark: "",
});
const add_fun = () => {
  add_table.value = [];
  add_table.value.push(JSON.parse(JSON.stringify(add_table_item.value)));
  show_box.value = true;
};
const add_table_item = ref({
  type: "1",
  value: "",
  sort: 1,
});
const add_table = ref([]);
const add_table_row = () => {
  add_table_item.value.sort = add_table.value.length + 1;
  add_table.value.push(JSON.parse(JSON.stringify(add_table_item.value)));
};

const metadata_pageData = ref({
  // 元数据列表
  current: 1,
  pageSize: 1000,
  name: "",
  templateIdList: [],
  metadataInfo: {
    isUse: 1,
  },
  isUse: 1,
});
const metadata_list = ref();
const list = ref();
const total = ref();
const loading = ref(false);
const btn_loading = ref(false);
const event_param = ref();

const currentRowIndex = ref(0);
const row_id = ref("");
const get_list_info = (e) => {
  console.log(e);
  if (row_id.value == e) return;
  row_id.value = e;
  EventBus.emit("number_id", {
    id: e,
    tem_id: page_data.value.identifierId,
    temId_list: metadata_pageData.value.templateIdList,
  });
};
const max_height = ref();
const show_num_table = ref(false);
onMounted(() => {
  max_height.value = window.innerHeight - 350; // 不带分页的 table 高度
  page_data.value = {
    current: 1,
    pageSize: 10,
    identifierId: "",
  };
  add_form_data.value = {
    id: "",
    identifierId: "",
    code: "",
    drawingType: "1",
    figureNo: "",
    sort: "",
    mainCode: "",
    sort_type: 1,
    remark: "",
  };
  show_num_table.value = false;
  if (props.rule_type == 1) {
    metadata_pageData.value = Object.assign(metadata_pageData.value, {
      isAttribute: true,
    });
  } else if (props.rule_type == 2) {
    metadata_pageData.value = Object.assign(metadata_pageData.value, {
      isPartsAttribute: true,
    });
  } else if (props.rule_type == 3) {
    metadata_pageData.value = Object.assign(metadata_pageData.value, {
      isMyPartsAttribute: true,
    });
  }
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item);
  });
  EventBus.on("rule_id", (e) => {
    console.log(e);
    currentRowIndex.value = 0;
    metadata_pageData.value.templateIdList = [];
    event_param.value = e;
    page_data.value.identifierId = event_param.value.id;
    add_form_data.value.identifierId = event_param.value.id;
    event_param.value.templateId_list.forEach((item) => {
      metadata_pageData.value.templateIdList.push(item.templateId);
    });
    get_list();
    if (add_form_data.value.identifierId != "") get_metadata_list();
  });
  EventBus.on("show_rule_table", () => {
    show_num_table.value = !show_num_table.value;
  });
});
onUnmounted(() => {
  EventBus.off("rule_id");
  EventBus.off("show_rule_table");
  list.value = [];
  total.value = 0;
});
const move_list = (e) => {
  add_form_data.value = {
    id: e.item.id,
    identifierId: add_form_data.value.identifierId,
    code: e.item.code,
    drawingType: e.item.drawingType + "",
    figureNo: e.item.figureNo,
    sort: e.type == 1 ? list.value[e.index - 1].sort : list.value[e.index + 1].sort,
    mainCode: e.mainCode,
    sort_type: 1,
    remark: e.item.remark,
  };
  move_submit();
};
const move_submit = () => {
  axios
    .request({
      url: serviceApi.number_crud + "/" + add_form_data.value.id,
      method: "PUT",
      data: add_form_data.value,
    })
    .then(() => {
      get_list();
      add_form_data.value = {
        id: "",
        identifierId: add_form_data.value.identifierId,
        code: "",
        drawingType: "1",
        figureNo: "",
        sort: "",
        mainCode: "",
        sort_type: 1,
        remark: "",
      };
      show_box.value = false;
      ElMessage.success("操作成功！");
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const copy_list = (e) => {
  axios
    .request({ url: serviceApi.copy_number + "/" + e.id, method: "post" })
    .then(() => {
      ElMessage.success("操作成功！");
      get_list();
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const show_delete_box = ref(false);
const delete_box_status = ref();
const delete_id = ref();
const delete_name = ref();
const delete_list = (e) => {
  console.log(e);
  delete_box_status.value = e.type;
  show_delete_box.value = true;
  delete_id.value = e.item.id;
  delete_name.value = e.item.name;
};
const submit_delete = () => {
  axios
    .request({
      url: serviceApi.number_crud + "/" + delete_id.value,
      method: "delete",
    })
    .then((res) => {
      console.log(res);
      ElMessage.success("删除成功！");
      show_delete_box.value = false;
      get_list();
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const edit_list = (e) => {
  add_table.value = [];
  add_form_data.value = {
    id: e.id,
    identifierId: add_form_data.value.identifierId,
    code: e.code,
    drawingType: e.drawingType + "",
    figureNo: e.figureNo,
    sort: e.sort,
    mainCode: e.mainCode,
    sort_type: 1,
    remark: e.remark,
  };
  // 编号格式转换 数据回填
  let list = e.code.split("}{");
  console.log(list);
  if (list.length == 1) {
    console.log(list[0].search("%"));
    var i = {
      type: list[0].search("%") != -1 ? "1" : "2",
      value: list[0].replace("}", "").replace("%", "").replace("{", ""),
      sort: 1,
    };
    add_table.value.push(i);
  } else {
    list.forEach((item, index) => {
      console.log(item.search("%"));
      if (item.search("%") != -1) {
        var i = {
          type: "1",
          value: item.split("%")[1].replace("}", "").replace("{", ""),
          sort: index + 1,
        };
      } else {
        var i = {
          type: "2",
          value: item.replace("}", "").replace("{", ""),
          sort: index + 1,
        };
      }
      add_table.value.push(i);
    });
  }
  show_box.value = true;
};
const submit = async (formEl: FormInstance | undefined) => {
  console.log(add_table.value);
  add_form_data.value.code = "";
  for (let i in add_table.value) {
    if (add_table.value[i].value == "") {
      ElMessage.error("列表中存在参数值为空的记录，请删除或填写该值");
      return;
    }
    if (add_table.value[i].type == 1) {
      add_table.value[i].value_code = "{%" + add_table.value[i].value + "}";
    } else {
      add_table.value[i].value_code = "{" + add_table.value[i].value + "}";
    }
    add_form_data.value.code += add_table.value[i].value_code;
  }
  if (add_form_data.value.id == "") {
    add_form_data.value.sort =
      add_form_data.value.sort_type == 1
        ? list.value.length
          ? list.value.at(-1).sort + 1
          : 1
        : 1;
  }
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return;
      btn_loading.value = true;
      axios
        .request({
          url:
            add_form_data.value.id == ""
              ? serviceApi.number_crud
              : serviceApi.number_crud + "/" + add_form_data.value.id,
          method: add_form_data.value.id == "" ? "post" : "PUT",
          data: add_form_data.value,
        })
        .then((res) => {
          console.log(res);
          btn_loading.value = false;
          get_list();
          resetForm(formEl);
          ElMessage.success("操作成功！");
        })
        .catch((err) => {
          btn_loading.value = false;
          ElMessage.error(err);
        });
    }
  });
};
const table = ref(null);
const get_list = () => {
  axios
    .request({
      url: serviceApi.number_list,
      method: "POST",
      data: page_data.value,
    })
    .then((res) => {
      console.log(res);
      if (currentRowIndex.value >= res.data.content.length) {
        currentRowIndex.value = res.data.content.length - 1;
      }
      if (res.data.content.length) {
        table.value.setCurrentRow(res.data.content[currentRowIndex.value]);
        get_list_info(res.data.content[currentRowIndex.value].id);
        res.data.content.forEach((item) => {
          let i = "";
          let code_list = item.code.split("}{");
          code_list.forEach((item1) => {
            if (item1.search("%") != -1) {
              i += "%";
            } else {
              i += item1.replace("}", "").replace("{", "");
            }
          });
          item.table_code = i;
        });
      } else {
        get_list_info("");
      }
      list.value = res.data.content;
      total.value = parseInt(res.data.totalElements);
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};

let list_debounce = debounce(200, get_list);
const get_metadata_list = () => {
  axios
    .request({
      url: serviceApi.metadata_list,
      method: "post",
      data: metadata_pageData.value,
    })
    .then((res) => {
      console.log(res);
      metadata_list.value = res.data.content;
    });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  add_form_data.value = {
    id: "",
    identifierId: add_form_data.value.identifierId,
    code: "",
    drawingType: "1",
    figureNo: "",
    sort: "",
    mainCode: "",
    sort_type: 1,
    remark: "",
  };
  show_box.value = false;
};
</script>

<style lang="scss" scoped>
.top_title {
  display: flex;
  align-items: center;
  padding: 2px 5px;
  border: 1px solid #666;
  border-radius: 10px;
  color: #666;
  cursor: pointer;
  &:hover {
    border-color: #3580eb;
    color: #3580eb;
  }
}
.select_me {
  transform: rotate(90deg);
}
.table_header {
  display: flex;
  justify-content: space-between;
  text-align: center;
  background-color: #f1f1f1;
  height: 40px;
  line-height: 40px;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  span {
    display: inline-block;
    border-right: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
  }
}
</style>
